#include "alarm.h"
#include "ds3231_rtc.h"
#include "buzzer.h"
#include "segment_codes.h"
#include "LOG.h"
#include "FreeRTOS.h"
#include "task.h"
#include "rotary_encoder.h"
#include "ht1621b.h"

// 当前正在设置的闹钟ID（0表示没有设置）
static uint8_t current_setting_alarm_id = 0;

// 闹钟初始化
void alarm_init(void) {
    // 初始化闹钟1
    alarms[0].id = 1;
    alarms[0].time.alarm_time.hours = 0;
    alarms[0].time.alarm_time.minutes = 0;
    alarms[0].time.status = TICK_STATUS_STOPPED;
    alarms[0].repeat = false;
    alarms[0].repeat_days = 0x7F;  // 默认每天重复
    
    // 初始化闹钟2
    alarms[1].id = 2;
    alarms[1].time.alarm_time.hours = 0;
    alarms[1].time.alarm_time.minutes = 0;
    alarms[1].time.status = TICK_STATUS_STOPPED;
    alarms[1].repeat = false;
    alarms[1].repeat_days = 0x7F;  // 默认每天重复
    
    current_setting_alarm_id = 0;
    LOG_INFO("Alarm module initialized");
}

// 设置闹钟时间
bool alarm_set_time(uint8_t id, uint8_t hours, uint8_t minutes) {
    if (id < 1 || id > 2) {
        LOG_WARN("Invalid alarm ID: %d", id);
        return false;
    }
    
    if (hours > 23 || minutes > 59) {
        LOG_WARN("Invalid alarm time: %02d:%02d", hours, minutes);
        return false;
    }
    
    alarms[id-1].time.alarm_time.hours = hours;
    alarms[id-1].time.alarm_time.minutes = minutes;
    
    LOG_INFO("Alarm %d time set to %02d:%02d", id, hours, minutes);
    return true;
}

// 获取闹钟时间
bool alarm_get_time(uint8_t id, tick_time_t* time) {
    if (id < 1 || id > 2 || time == NULL) {
        LOG_WARN("Invalid alarm ID or null pointer");
        return false;
    }
    
    time->alarm_time.hours = alarms[id-1].time.alarm_time.hours;
    time->alarm_time.minutes = alarms[id-1].time.alarm_time.minutes;
    
    return true;
}

// 启用/禁用闹钟
bool alarm_enable(uint8_t id, bool enable) {
    if (id < 1 || id > 2) {
        LOG_WARN("Invalid alarm ID: %d", id);
        return false;
    }
    
    if (enable) {
        alarms[id-1].time.status = TICK_STATUS_RUNNING;
        LOG_INFO("Alarm %d enabled", id);
    } else {
        alarms[id-1].time.status = TICK_STATUS_STOPPED;
        LOG_INFO("Alarm %d disabled", id);
    }
    
    return true;
}

// 检查闹钟是否启用
bool alarm_is_enabled(uint8_t id) {
    if (id < 1 || id > 2) {
        return false;
    }
    
    return (alarms[id-1].time.status == TICK_STATUS_RUNNING);
}

// 检查闹钟是否正在响铃
bool alarm_is_ringing(uint8_t id) {
    if (id < 1 || id > 2) {
        return false;
    }
    
    return (alarms[id-1].time.status == TICK_STATUS_RUNNING);
}

// 停止闹钟响铃
void alarm_stop_ringing(uint8_t id) {
    if (id < 1 || id > 2) {
        return;
    }
    
    if (alarms[id-1].time.status == TICK_STATUS_RUNNING) {
        alarms[id-1].time.status = TICK_STATUS_STOPPED;
        LOG_INFO("Alarm %d stopped ringing", id);
    }
}

// 设置闹钟重复
void alarm_set_repeat(uint8_t id, bool repeat) {
    if (id < 1 || id > 2) {
        return;
    }
    
    alarms[id-1].repeat = repeat;
    LOG_INFO("Alarm %d repeat set to %s", id, repeat ? "true" : "false");
}

// 设置闹钟重复天数
void alarm_set_repeat_days(uint8_t id, uint8_t days) {
    if (id < 1 || id > 2) {
        return;
    }
    
    alarms[id-1].repeat_days = days & 0x7F;  // 只取低7位
    LOG_INFO("Alarm %d repeat days set to 0x%02X", id, days);
}

// 进入闹钟设置模式
void alarm_setting(uint8_t id) {
    if (id < 1 || id > 2) {
        return;
    }
    
    current_setting_alarm_id = id;
    alarms[id-1].time.status = TICK_STATUS_SETTING;
    LOG_INFO("Alarm %d setting mode activated", id);
    
    // 显示当前闹钟时间
    ht1621b_clear_buffer();
    segment_display_RTC_time(alarms[id-1].time.alarm_time.hours, 
                           alarms[id-1].time.alarm_time.minutes, 0, true);
    segment_display_function_indicator(id, true);  // 显示闹钟1或2的指示器
    ht1621b_display_update();
}

// 退出闹钟设置模式
void alarm_setting_confirm(void) {
    if (current_setting_alarm_id == 0) {
        return;
    }
    
    uint8_t id = current_setting_alarm_id;
    alarms[id-1].time.status = TICK_STATUS_STOPPED;
    current_setting_alarm_id = 0;
    LOG_INFO("Alarm %d setting confirmed", id);
}

// 显示闹钟时间
void alarm_display_time(uint8_t id, bool colon_visible) {
    if (id < 1 || id > 2) {
        return;
    }
    
    ht1621b_clear_buffer();
    segment_display_RTC_time(alarms[id-1].time.alarm_time.hours, 
                           alarms[id-1].time.alarm_time.minutes, 0, colon_visible);
    segment_display_function_indicator(id, true);
    ht1621b_display_update();
}

// 处理旋转编码器事件
void alarm_handle_rotary_event(void) {
    if (current_setting_alarm_id == 0) {
        return;  // 不在设置模式
    }
    
    rotary_event_t rotary_event = rotary_encoder_process();
    uint8_t id = current_setting_alarm_id;
    
    switch (rotary_event) {
        case ROTARY_EVENT_CLOCKWISE:
            // 顺时针旋转增加分钟
            if (alarms[id-1].time.alarm_time.minutes < 59) {
                alarms[id-1].time.alarm_time.minutes++;
            } else {
                alarms[id-1].time.alarm_time.minutes = 0;
                if (alarms[id-1].time.alarm_time.hours < 23) {
                    alarms[id-1].time.alarm_time.hours++;
                } else {
                    alarms[id-1].time.alarm_time.hours = 0;
                }
            }
            LOG_INFO("Alarm %d time increased to %02d:%02d", 
                     id, alarms[id-1].time.alarm_time.hours, alarms[id-1].time.alarm_time.minutes);
            
            // 更新显示
            alarm_display_time(id, true);
            break;
            
        case ROTARY_EVENT_COUNTERCLOCKWISE:
            // 逆时针旋转减少分钟
            if (alarms[id-1].time.alarm_time.minutes > 0) {
                alarms[id-1].time.alarm_time.minutes--;
            } else {
                alarms[id-1].time.alarm_time.minutes = 59;
                if (alarms[id-1].time.alarm_time.hours > 0) {
                    alarms[id-1].time.alarm_time.hours--;
                } else {
                    alarms[id-1].time.alarm_time.hours = 23;
                }
            }
            LOG_INFO("Alarm %d time decreased to %02d:%02d", 
                     id, alarms[id-1].time.alarm_time.hours, alarms[id-1].time.alarm_time.minutes);
            
            // 更新显示
            alarm_display_time(id, true);
            break;
            
        case ROTARY_EVENT_BUTTON_PRESSED:
            // 按钮按下确认设置
            alarm_setting_confirm();
            break;
            
        case ROTARY_EVENT_BUTTON_LONG_PRESSED:
            // 长按切换小时/分钟设置（可选功能）
            // 这里可以添加切换设置小时/分钟的功能
            break;
            
        case ROTARY_EVENT_NONE:
        default:
            // 无事件
            break;
    }
}

// 检查当前时间是否匹配闹钟时间
bool alarm_check_time(const rtc_time_t* current_time) {
    if (current_time == NULL) {
        return false;
    }
    
    // 检查秒数是否为0（整分钟）
    if (current_time->seconds != 0) {
        return false;
    }
    
    bool alarm_triggered = false;
    
    // 检查每个闹钟
    for (int i = 0; i < 2; i++) {
        // 检查闹钟是否启用
        if (alarms[i].time.status != TICK_STATUS_RUNNING) {
            continue;
        }
        
        // 检查时间是否匹配
        if (current_time->hours == alarms[i].time.alarm_time.hours && 
            current_time->minutes == alarms[i].time.alarm_time.minutes) {
            
            // 检查是否在重复天数内（如果设置了重复）
            if (alarms[i].repeat && alarms[i].repeat_days != 0) {
                uint8_t day_bit = 1 << (current_time->weekday - 1);  // 星期日=bit0
                if (!(alarms[i].repeat_days & day_bit)) {
                    continue;  // 不在重复天数内
                }
            }
            
            // 触发闹钟
            alarms[i].time.status = TICK_STATUS_RUNNING;
            alarm_triggered = true;
            LOG_INFO("Alarm %d triggered at %02d:%02d", alarms[i].id, 
                     current_time->hours, current_time->minutes);
        }
    }
    
    return alarm_triggered;
}

// 闹钟处理函数
void alarm_process(void) {
    // 检查是否有闹钟正在响铃
    for (int i = 0; i < 2; i++) {
        if (alarms[i].time.status == TICK_STATUS_RUNNING)
        {
            // 触发蜂鸣器响铃
            buzzer_beep(1000);  // 1秒鸣响
            LOG_INFO("Alarm %d is ringing", alarms[i].id);
            
            // 如果不重复，则禁用闹钟
            if (!alarms[i].repeat) {
                alarms[i].time.status = TICK_STATUS_STOPPED;
                LOG_INFO("Alarm %d disabled (non-repeating)", alarms[i].id);
            }
        }
    }
}
